package com.avic.rong.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.adapter.TradingAdapter;
import com.avic.rong.api.my_message.MyMessageApi;
import com.avic.rong.api.my_message.ReadMessageApi;
import com.avic.rong.bean.my_message.MessageBean;
import com.avic.rong.userOrder.MineMessageEvent;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class TradingFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener{


    @BindView(R.id.srl_trad)
    SmartRefreshLayout srl_trad;
    private String token = "";
    private ArrayList<MessageBean> mList = new ArrayList<>();

    private Integer pageNumber = 1;
    private Integer pageSize = 10;
    private TradingAdapter tradingAdapter;
    private MyMessageApi myMessageApi;
    private boolean isRefresh;

    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    private int REFRESH = 200;


    //测试用的token
   // private String token = "w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvty5QOPgq/+YLF2xTVRyFnfxTic0l1spU1DKp8PMVM1YSixxW8qPiUHQ9CAb6QSHI";


    @BindView(R.id.recv_trading)
    RecyclerView mRecv;


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.CART_BROADCAST");
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent){
                String msg = intent.getStringExtra("data");
                if("refresh".equals(msg)){
                    initData();
                }
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_trading, container, false);

        ButterKnife.bind(this, inflate);
        EventBus.getDefault().register(this);


//        loading_layout = inflate.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);
        loading_layout.hideReturnButton();


        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(myMessageApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });


        Log.e("TradingFragment", " login_stoken  :" + token);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        mRecv.setLayoutManager(linearLayoutManager);
        tradingAdapter = new TradingAdapter(getContext(), mList);
        mRecv.setAdapter(tradingAdapter);

        srl_trad.setOnRefreshLoadMoreListener(this);

        return inflate;
    }

    private void initData() {

        myMessageApi = new MyMessageApi((MainActivity) getActivity(), myMessageListener);
        if (SharedPreferencesUtil.isLogin()) {
            mList.clear();
            token = SharedPreferencesUtil.getLoginToken();
            myMessageApi.setArgument(token, pageNumber, pageSize);
            HttpManager.getInstance().doHttpDeal(myMessageApi);
        }

           // tradingAdapter.notifyDataSetChanged();
    }

    HttpOnNextListener<BaseResultEntity> myMessageListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                List<MessageBean> list = (List<MessageBean>) baseResultEntity.getData();
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                //消息标记已读
                readMsg();
                if (list!=null&&list.size()>0) {
                    if (isRefresh) {
                        mList.clear();
                    }

                    if (list != null && list.size() > 0) {
                        mList.addAll(list);
                    }
                    tradingAdapter.notifyDataSetChanged();
                    if (isRefresh) {
                        srl_trad.finishRefresh();
                    } else {
                        srl_trad.finishLoadMore();
                    }
                }
                if (mList!=null&&mList.size()<=0){
                    loading_layout.setStatus(LoadingLayout.EMPTY);
                    loading_layout.setEmptyImageVisible(true);
                    loading_layout.setEmptyImage(R.mipmap.empty_msg);
                    loading_layout.setEmptyText("您还没有消息哦~");
                }

            }else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void readMsg() {
        ReadMessageApi readMessageApi = new ReadMessageApi((MainActivity) getActivity(),readMsgListener);
        readMessageApi.setArgument(token);
        HttpManager.getInstance().doHttpDeal(readMessageApi);
    }

    //消息标记已读
    HttpOnNextListener<BaseResultEntity> readMsgListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                ToastTools.showToast(baseResultEntity.getMsg());
            }
        }
    };

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        pageNumber = pageNumber + 1;
        myMessageApi.setPageNumber(pageNumber);
        HttpManager.getInstance().doHttpDeal(myMessageApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh  = true;
        pageNumber = 1;
        myMessageApi.setPageNumber(pageNumber);
        HttpManager.getInstance().doHttpDeal(myMessageApi);
    }
    /**
     * 点击底部按钮刷新消息数据
     *
     * @param mineMessageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void massageInform(MineMessageEvent mineMessageEvent) {
        srl_trad.autoRefresh();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void loadData() {
        initData();
    }
}
